package com.jyxd.web.controller.basic;

import com.jyxd.web.data.basic.CustomContent;
import com.jyxd.web.data.basic.CustomField;
import com.jyxd.web.data.basic.InOutAmount;
import com.jyxd.web.data.basic.MedOrderExecRecord;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.dto.InOutAmountStatisticRequestDTO;
import com.jyxd.web.data.user.User;
import com.jyxd.web.service.assessment.basic.*;
import com.jyxd.web.util.HttpCode;
import com.jyxd.web.util.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jyxd.web.util.DateUtil.*;

@Api(tags = "出入量（二合一）相关接口")
@Controller
@RequestMapping(value = "/inOutAmount")
public class InOutAmountController {

    private static Logger logger = LoggerFactory.getLogger(InOutAmountController.class);

    @Autowired
    private InOutAmountService inOutAmountService;

    @Autowired
    private CustomFieldService customFieldService;

    @Autowired
    private CustomContentService customContentService;
    @Autowired
    private InOUtAmountStatisticsService inOUtAmountStatisticsService;

    @Autowired
    private MedOrderExecService medOrderExecService;

    @Autowired
    private MedOrderExecRecordService medOrderExecRecordService;


    /**
     * 增加一条出入量表（二表合一）记录
     *
     * @return
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody InOutAmount inOutAmount) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "添加失败");
        inOutAmount.setId(UUIDUtil.getUUID());
        inOutAmount.setCreateTime(new Date());
        inOutAmountService.insert(inOutAmount);
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg", "添加成功");
        return json.toString();
    }

    /**
     * 更新出入量表（二表合一）状态
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "更新失败");
        if (map != null && map.containsKey("id") && map.containsKey("status")) {
            InOutAmount inOutAmount = inOutAmountService.queryData(map.get("id").toString());
            if (inOutAmount != null) {
                inOutAmount.setStatus((int) map.get("status"));
                inOutAmountService.update(inOutAmount);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 编辑出入量表（二表合一）记录单
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "编辑失败");
        if (map != null && map.containsKey("id") && map.containsKey("status") && map.containsKey("bedName")) {
            InOutAmount inOutAmount = inOutAmountService.queryData(map.get("id").toString());
            if (inOutAmount != null) {
                inOutAmount.setStatus((int) map.get("status"));
                inOutAmountService.update(inOutAmount);
                json.put("msg", "编辑成功");
            } else {
                json.put("msg", "编辑失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());

        return json.toString();
    }

    /**
     * 删除出入量表（二表合一）记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        if (map.containsKey("id")) {
            InOutAmount inOutAmount = inOutAmountService.queryData(map.get("id").toString());
            if (inOutAmount != null) {
                inOutAmount.setStatus(-1);
                inOutAmountService.update(inOutAmount);
                // 删除关联表自定义内容id
                customContentService.updateByAssociatedTableId(inOutAmount.getId());
                json.put("msg", "删除成功");
            } else {
                json.put("msg", "删除失败，没有这个对象。");
                return json.toString();
            }

        }
        if (StringUtils.isNotEmpty(map.get("orderCode").toString())) {
            Map<String, Object> selectMap = new HashMap<String, Object>();
            selectMap.put("orderNo", map.get("orderCode").toString());
            List<MedOrderExecRecord> medOrderExecRecords = medOrderExecRecordService.queryList(selectMap);
            if (medOrderExecRecords.size() > 0) {
                for (int i = 0; i < medOrderExecRecords.size(); i++) {
                    medOrderExecRecords.get(i).setStatus(-1);
                    medOrderExecRecordService.update(medOrderExecRecords.get(i));
                }
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据主键id查询出入量表（二表合一）记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("id")) {
            InOutAmount inOutAmount = inOutAmountService.queryData(map.get("id").toString());
            if (inOutAmount != null) {
                json.put("msg", "查询成功");
                json.put("data", JSONObject.fromObject(inOutAmount));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 导出出入量信息统计excel
     *
     * @return
     */
    @ApiOperation("导出出入量信息统计excel")
    @RequestMapping(value = "/downloadInOutTotal", method = RequestMethod.POST)
    public void downloadInOutTotal(@RequestBody(required = false) InOutAmountStatisticRequestDTO inOutAmountStatisticRequestDTO, HttpServletResponse response) throws Exception {
        try {
            inOUtAmountStatisticsService.exportExcelTotalStatistic(inOutAmountStatisticRequestDTO, response);
        } catch (Exception e) {
            response.getWriter().print("内部服务异常");
            e.printStackTrace();
        }
    }


    /**
     * 病人管理-护理文书-护理单文书-出入量-根据条件查询出入量列表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getInOutAmountList", method = RequestMethod.POST)
    @ResponseBody
    public String getInOutAmountList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map == null || !map.containsKey("patientId") || StringUtils.isEmpty(map.get("patientId").toString())) {
            json.put("code", HttpCode.NO_PATIENT_CODE.getCode());
            json.put("msg", "请选择病人");
            return json.toString();
        }
        if (map != null && map.containsKey("start")) {
            int totalCount = inOutAmountService.getInOutAmountNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        //先查询有哪些自定义字段，放入查询条件中
        Map<String, Object> m = new HashMap<>();
        m.put("status", 1);
        m.put("associatedTable", "table_in_out_amount");//关联表名
        List<CustomField> list = customFieldService.queryList(m);
        if (list != null && list.size() > 0) {
            map.put("list", list);
        }
        List<Map<String, Object>> amountList = inOutAmountService.getInOutAmountList(map);
        if (amountList != null && amountList.size() > 0) {
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(amountList));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 病人管理-护理文书-护理单文书-出入量-根据条件查询并统计出入量列表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/statistics", method = RequestMethod.POST)
    @ResponseBody
    public String statistics(@RequestBody(required = false) Map<String, Object> map) throws ParseException {
        return inOUtAmountStatisticsService.statistics(map);
    }

    /**
     * 病人管理-护理文书-护理单文书-出入量-根据条件查询并统计时间段内出入量列表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/timeQuantumStatistics", method = RequestMethod.POST)
    @ResponseBody
    public String timeQuantumStatistics(@RequestBody(required = false) Map<String, Object> map) throws Exception {
        return inOUtAmountStatisticsService.timeQuantumStatistics(map);
    }

    /**
     * 病人管理-护理文书-护理单文书-出入量-根据条件查询并统计时间段内出入量列表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    public void saveStatisticsData(@RequestBody(required = false) Map<String, Object> map) throws Exception {
        inOUtAmountStatisticsService.saveStatisticsData(map);
    }

    /**
     * 病人管理-出入量
     *
     * @param
     * @return
     */
    @ApiOperation("出入量按时间总统计接口")
    @RequestMapping(value = "/totalStatistics",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult totalStatistic(@RequestBody(required = false) InOutAmountStatisticRequestDTO inOutAmountStatisticRequestDTO) {
        return inOUtAmountStatisticsService.totalStatistic(inOutAmountStatisticRequestDTO);
    }

    /**
     * 病人管理-出入量
     *
     * @param
     * @return
     */
    @ApiOperation("出入量按时间查询数据总量")
    @RequestMapping(value = "/getInAndOutTotal",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult getInAndOutTotal(@RequestBody(required = false) InOutAmountStatisticRequestDTO inOutAmountStatisticRequestDTO) {
        return inOUtAmountStatisticsService.getInAndOutTotal(inOutAmountStatisticRequestDTO);
    }

    /**
     * 病人管理-护理文书-护理单文书-出入量-保存出入量
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/saveData")
    @ResponseBody
    public String saveData(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "失败");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        User user = (User) session.getAttribute("user");
        //判断结束时间是否大于开始时间
        if (Objects.nonNull(map.get("startTime")) && Objects.nonNull(map.get("endTime"))
                && StringUtils.isNotBlank(map.get("startTime") + "")
                && StringUtils.isNotBlank(map.get("endTime") + "")) {
            try {
                boolean judgeSize = judgeSize(yyyyMMddHHmmssSdfToDate(map.get("startTime").toString()), yyyyMMddHHmmssSdfToDate(map.get("endTime").toString()));
                if (!judgeSize) {
                    json.put("msg", "结束时间小于等于开始时间，请重新选择！");
                    return json.toString();
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        try {
            if (map != null && map.containsKey("id") && !map.get("id").equals("")) {
                //有id 编辑
                InOutAmount inOutAmount = inOutAmountService.queryData(map.get("id").toString());
                if (inOutAmount != null) {
                    inOutAmount.setStatus(map.containsKey("status") && StringUtils.isNotEmpty(map.get("status").toString()) ? Integer.valueOf(map.get("status").toString()) : 1);
                    inOutAmount.setDataTime(map.containsKey("dataTime") && StringUtils.isNotEmpty(map.get("dataTime").toString()) ? format.parse(map.get("dataTime").toString()) : null);
                    if (map.containsKey("orderId") && StringUtils.isNotEmpty(map.get("orderId").toString()) && map.containsKey("orderTime") && StringUtils.isNotEmpty(map.get("orderTime").toString())) {
                        if (StringUtils.isNotEmpty(inOutAmount.getOrderCode()) && !map.get("orderId").toString().equals(inOutAmount.getOrderCode())) {//如果本次传入的医嘱id与原先不同，则删除原先的医嘱记录表
                            Map<String, Object> selectMap = new HashMap<String, Object>();
                            selectMap.put("orderNo", inOutAmount.getOrderCode());
                            List<MedOrderExecRecord> medOrderExecRecords = medOrderExecRecordService.queryList(selectMap);
                            if (medOrderExecRecords.size() > 0) {
                                for (int i = 0; i < medOrderExecRecords.size(); i++) {
                                    medOrderExecRecords.get(i).setStatus(-1);
                                    medOrderExecRecordService.update(medOrderExecRecords.get(i));
                                }
                            }

                        }
                        medOrderExecService.orderRecord(map.get("orderId").toString(), user, map.get("orderTime").toString());
                    }
                    inOutAmount.setOrderCode(map.containsKey("orderId") && StringUtils.isNotEmpty(map.get("orderId").toString()) ? map.get("orderId").toString() : null);
                    inOutAmount.setOrderNo(map.containsKey("orderNo") && StringUtils.isNotEmpty(map.get("orderNo").toString()) ? map.get("orderNo").toString() : null);
                    inOutAmount.setOrderSubNo(map.containsKey("orderSubNo") && StringUtils.isNotEmpty(map.get("orderSubNo").toString()) ? map.get("orderSubNo").toString() : null);
                    inOutAmount.setOrderName(map.containsKey("orderName") && StringUtils.isNotEmpty(map.get("orderName").toString()) ? map.get("orderName").toString() : null);
                    inOutAmount.setDosage(map.containsKey("dosage") && StringUtils.isNotEmpty(map.get("dosage").toString()) ? map.get("dosage").toString() : null);
                    inOutAmount.setAllowanceDosage(map.containsKey("allowanceDosage") && StringUtils.isNotEmpty(map.get("allowanceDosage").toString()) ? map.get("allowanceDosage").toString() : null);
                    inOutAmount.setSurplus(map.containsKey("surplus") && StringUtils.isNotEmpty(map.get("surplus").toString()) ? map.get("surplus").toString() : null);
                    inOutAmount.setPiss(map.containsKey("piss") && StringUtils.isNotEmpty(map.get("piss").toString()) ? map.get("piss").toString() : null);
                    inOutAmount.setFaces(map.containsKey("faces") && StringUtils.isNotEmpty(map.get("faces").toString()) ? map.get("faces").toString() : null);
                    inOutAmount.setDrainage(map.containsKey("drainage") && StringUtils.isNotEmpty(map.get("drainage").toString()) ? map.get("drainage").toString() : null);
                    inOutAmount.setRemark(map.containsKey("remark") && StringUtils.isNotEmpty(map.get("remark").toString()) ? map.get("remark").toString() : null);
                    inOutAmount.setSignatureOneImage((String) map.get("signatureOneImage"));
                    inOutAmount.setSignatureTwoImage((String) map.get("signatureTwoImage"));
                    inOutAmount.setSignature(map.containsKey("signature") && StringUtils.isNotEmpty(map.get("signature").toString()) ? map.get("signature").toString() : null);
                    inOutAmount.setCheckSignature(map.containsKey("checkSignature") && StringUtils.isNotEmpty(map.get("checkSignature").toString()) ? map.get("checkSignature").toString() : null);
                    inOutAmount.setIllnessRecords(map.containsKey("illnessRecords") && StringUtils.isNotEmpty(map.get("illnessRecords").toString()) ? map.get("illnessRecords").toString() : null);
                    inOutAmount.setBalance(map.containsKey("balance") && StringUtils.isNotEmpty(map.get("balance").toString()) ? map.get("balance").toString() : null);
                    inOutAmount.setStartTime(map.containsKey("startTime") && StringUtils.isNotEmpty(map.get("startTime").toString()) ? format.parse(map.get("startTime").toString()) : null);
                    inOutAmount.setEndTime(map.containsKey("endTime") && StringUtils.isNotEmpty(map.get("endTime").toString()) ? format.parse(map.get("endTime").toString()) : null);
                    inOutAmount.setRate(map.containsKey("rate") && StringUtils.isNotEmpty(map.get("rate").toString()) ? map.get("rate").toString() : null);
                    inOutAmount.setUseSign(map.containsKey("useSign") && StringUtils.isNotEmpty(map.get("useSign").toString()) ? map.get("useSign").toString() : null);
                    inOutAmount.setParentId(map.containsKey("parent_id") && StringUtils.isNotEmpty(map.get("parent_id").toString()) ? map.get("parent_id").toString() : null);
                    if (user != null) {
                        inOutAmount.setOperatorCode(user.getLoginName());
                    }
                   /* if (StringUtils.isEmpty(inOutAmount.getSurplus())) {//如果传入的余量为空，则赋值为0
                        inOutAmount.setSurplus("0");
                    }*/
                    //如果备用量、余量不为空，则计算实入量
                    if (StringUtils.isNotEmpty(inOutAmount.getAllowanceDosage()) &&
                            StringUtils.isNotEmpty(inOutAmount.getSurplus()) && !StringUtils.equals(inOutAmount.getSurplus(), "") &&
                            (StringUtils.isEmpty(inOutAmount.getDosage()) || StringUtils.equals(inOutAmount.getDosage(), "0"))) {
                        double dosage = Double.valueOf(inOutAmount.getAllowanceDosage()) - Double.valueOf(inOutAmount.getSurplus());
                        inOutAmount.setDosage(String.valueOf(dosage));
                    }
                    // }
                    inOutAmount.setType(map.containsKey("type") && StringUtils.isNotEmpty(map.get("type").toString()) ? Integer.valueOf(map.get("type").toString()) : 1);
                    inOutAmountService.update(inOutAmount);
                    //根据时间 病人主键id 表名 查询对象
                    map.put("associatedTableId", inOutAmount.getId());
                    List<CustomContent> list = customContentService.getCustomContentByTime(map);
                    logger.info("请求字自定义字段查询 :" + list);
                    if (!CollectionUtils.isEmpty(list)) {
                        CustomContent customContent = list.get(0);
                        customContent.setAssociatedTableId(inOutAmount.getId());
                        customContent.setContentOne(map.containsKey("contentOne") && StringUtils.isNotEmpty(map.get("contentOne").toString()) ? map.get("contentOne").toString() : null);
                        customContent.setContentTwo(map.containsKey("contentTwo") && StringUtils.isNotEmpty(map.get("contentTwo").toString()) ? map.get("contentTwo").toString() : null);
                        customContent.setContentThree(map.containsKey("contentThree") && StringUtils.isNotEmpty(map.get("contentThree").toString()) ? map.get("contentThree").toString() : null);
                        customContent.setContentFour(map.containsKey("contentFour") && StringUtils.isNotEmpty(map.get("contentFour").toString()) ? map.get("contentFour").toString() : null);
                        customContent.setContentFive(map.containsKey("contentFive") && StringUtils.isNotEmpty(map.get("contentFive").toString()) ? map.get("contentFive").toString() : null);
                        customContent.setContentSix(map.containsKey("contentSix") && StringUtils.isNotEmpty(map.get("contentSix").toString()) ? map.get("contentSix").toString() : null);
                        customContent.setContentSeven(map.containsKey("contentSeven") && StringUtils.isNotEmpty(map.get("contentSeven").toString()) ? map.get("contentSeven").toString() : null);
                        customContent.setContentEight(map.containsKey("contentEight") && StringUtils.isNotEmpty(map.get("contentEight").toString()) ? map.get("contentEight").toString() : null);
                        customContent.setContentNine(map.containsKey("contentNine") && StringUtils.isNotEmpty(map.get("contentNine").toString()) ? map.get("contentNine").toString() : null);
                        customContent.setContentTen(map.containsKey("contentTen") && StringUtils.isNotEmpty(map.get("contentTen").toString()) ? map.get("contentTen").toString() : null);
                        customContent.setStatus("1");
                        customContentService.update(customContent);
                    } else {
                        CustomContent data = new CustomContent();
                        data.setId(UUIDUtil.getUUID());
                        data.setAssociatedTable(map.get("associatedTable").toString());
                        data.setPatientId(map.get("patientId").toString());
                        data.setDataTime(format.parse(map.get("dataTime").toString()));
                        data.setCreateTime(new Date());
                        data.setAssociatedTableId(inOutAmount.getId());
                        data.setContentOne(map.containsKey("contentOne") && StringUtils.isNotEmpty(map.get("contentOne").toString()) ? map.get("contentOne").toString() : null);
                        data.setContentTwo(map.containsKey("contentTwo") && StringUtils.isNotEmpty(map.get("contentTwo").toString()) ? map.get("contentTwo").toString() : null);
                        data.setContentThree(map.containsKey("contentThree") && StringUtils.isNotEmpty(map.get("contentThree").toString()) ? map.get("contentThree").toString() : null);
                        data.setContentFour(map.containsKey("contentFour") && StringUtils.isNotEmpty(map.get("contentFour").toString()) ? map.get("contentFour").toString() : null);
                        data.setContentFive(map.containsKey("contentFive") && StringUtils.isNotEmpty(map.get("contentFive").toString()) ? map.get("contentFive").toString() : null);
                        data.setContentSix(map.containsKey("contentSix") && StringUtils.isNotEmpty(map.get("contentSix").toString()) ? map.get("contentSix").toString() : null);
                        data.setContentSeven(map.containsKey("contentSeven") && StringUtils.isNotEmpty(map.get("contentSeven").toString()) ? map.get("contentSeven").toString() : null);
                        data.setContentEight(map.containsKey("contentEight") && StringUtils.isNotEmpty(map.get("contentEight").toString()) ? map.get("contentEight").toString() : null);
                        data.setContentNine(map.containsKey("contentNine") && StringUtils.isNotEmpty(map.get("contentNine").toString()) ? map.get("contentNine").toString() : null);
                        data.setContentTen(map.containsKey("contentTen") && StringUtils.isNotEmpty(map.get("contentTen").toString()) ? map.get("contentTen").toString() : null);
                        data.setStatus("1");
                        customContentService.insert(data);
                    }
                    json.put("msg", "更新成功");
                    json.put("code", HttpCode.OK_CODE.getCode());
                }
            } else {
                //没id 新增
                InOutAmount inOutAmount = new InOutAmount();
                Date newDate = new Date();
                inOutAmount.setId(UUIDUtil.getUUID());
                inOutAmount.setCreateTime(newDate);
                inOutAmount.setStatus(1);
                inOutAmount.setVisitId(map.containsKey("visitId") && StringUtils.isNotEmpty(map.get("visitId").toString()) ? map.get("visitId").toString() : null);
                inOutAmount.setVisitCode(map.containsKey("visitCode") && StringUtils.isNotEmpty(map.get("visitCode").toString()) ? map.get("visitCode").toString() : null);
                inOutAmount.setPatientId(map.containsKey("patientId") && StringUtils.isNotEmpty(map.get("patientId").toString()) ? map.get("patientId").toString() : null);
                inOutAmount.setDataTime(map.containsKey("dataTime") && StringUtils.isNotEmpty(map.get("dataTime").toString()) ? format.parse(map.get("dataTime").toString()) : null);
                inOutAmount.setOrderCode(map.containsKey("orderId") && StringUtils.isNotEmpty(map.get("orderId").toString()) ? map.get("orderId").toString() : null);
                if (map.containsKey("orderId") && StringUtils.isNotEmpty(map.get("orderId").toString()) && map.containsKey("orderTime") && StringUtils.isNotEmpty(map.get("orderTime").toString())) {
                    medOrderExecService.orderRecord(map.get("orderId").toString(), user, map.get("orderTime").toString());
                }
                inOutAmount.setOrderNo(map.containsKey("orderNo") && StringUtils.isNotEmpty(map.get("orderNo").toString()) ? map.get("orderNo").toString() : null);
                inOutAmount.setOrderSubNo(map.containsKey("orderSubNo") && StringUtils.isNotEmpty(map.get("orderSubNo").toString()) ? map.get("orderSubNo").toString() : null);
                inOutAmount.setOrderName(map.containsKey("orderName") && StringUtils.isNotEmpty(map.get("orderName").toString()) ? map.get("orderName").toString() : null);
                inOutAmount.setDosage(map.containsKey("dosage") && StringUtils.isNotEmpty(map.get("dosage").toString()) ? map.get("dosage").toString() : null);
                inOutAmount.setAllowanceDosage(map.containsKey("allowanceDosage") && StringUtils.isNotEmpty(map.get("allowanceDosage").toString()) ? map.get("allowanceDosage").toString() : null);
                inOutAmount.setSurplus(map.containsKey("surplus") && StringUtils.isNotEmpty(map.get("surplus").toString()) ? map.get("surplus").toString() : null);
                inOutAmount.setPiss(map.containsKey("piss") && StringUtils.isNotEmpty(map.get("piss").toString()) ? map.get("piss").toString() : null);
                inOutAmount.setFaces(map.containsKey("faces") && StringUtils.isNotEmpty(map.get("faces").toString()) ? map.get("faces").toString() : null);
                inOutAmount.setDrainage(map.containsKey("drainage") && StringUtils.isNotEmpty(map.get("drainage").toString()) ? map.get("drainage").toString() : null);
                inOutAmount.setRemark(map.containsKey("remark") && StringUtils.isNotEmpty(map.get("remark").toString()) ? map.get("remark").toString() : null);
                inOutAmount.setSignatureOneImage((String) map.get("signatureOneImage"));
                inOutAmount.setSignatureTwoImage((String) map.get("signatureTwoImage"));
                inOutAmount.setSignature(map.containsKey("signature") && StringUtils.isNotEmpty(map.get("signature").toString()) ? map.get("signature").toString() : null);
                inOutAmount.setCheckSignature(map.containsKey("checkSignature") && StringUtils.isNotEmpty(map.get("checkSignature").toString()) ? map.get("checkSignature").toString() : null);
                inOutAmount.setIllnessRecords(map.containsKey("illnessRecords") && StringUtils.isNotEmpty(map.get("illnessRecords").toString()) ? map.get("illnessRecords").toString() : null);
                inOutAmount.setBalance(map.containsKey("balance") && StringUtils.isNotEmpty(map.get("balance").toString()) ? map.get("balance").toString() : null);
                inOutAmount.setStartTime(map.containsKey("startTime") && StringUtils.isNotEmpty(map.get("startTime").toString()) ? format.parse(map.get("startTime").toString()) : null);
                inOutAmount.setEndTime(map.containsKey("endTime") && StringUtils.isNotEmpty(map.get("endTime").toString()) ? format.parse(map.get("endTime").toString()) : null);
                inOutAmount.setRate(map.containsKey("rate") && StringUtils.isNotEmpty(map.get("rate").toString()) ? map.get("rate").toString() : null);
                inOutAmount.setUseSign(map.containsKey("useSign") && StringUtils.isNotEmpty(map.get("useSign").toString()) ? map.get("useSign").toString() : null);
                inOutAmount.setParentId(map.containsKey("parent_id") && StringUtils.isNotEmpty(map.get("parent_id").toString()) ? map.get("parent_id").toString() : null);
                if (user != null) {
                    inOutAmount.setOperatorCode(user.getLoginName());
                }
                /*if (StringUtils.isEmpty(inOutAmount.getSurplus())) {//如果传入的余量为空，则赋值为0
                    inOutAmount.setSurplus("0");
                }*/
                //如果备用量、余量不为空，则计算实入量
                if (StringUtils.isNotEmpty(inOutAmount.getAllowanceDosage()) &&
                        StringUtils.isNotEmpty(inOutAmount.getSurplus()) && !StringUtils.equals(inOutAmount.getSurplus(), "") &&
                        (StringUtils.isEmpty(inOutAmount.getDosage()) || StringUtils.equals(inOutAmount.getDosage(), "0"))) {
                    double dosage = Double.valueOf(inOutAmount.getAllowanceDosage()) - Double.valueOf(inOutAmount.getSurplus());
                    inOutAmount.setDosage(String.valueOf(dosage));
                }
                inOutAmount.setType(map.containsKey("type") && StringUtils.isNotEmpty(map.get("type").toString()) ? Integer.valueOf(map.get("type").toString()) : 1);
                inOutAmountService.insert(inOutAmount);
                //新增自定义字段内容表
                if (map.containsKey("associatedTable") && StringUtils.isNotEmpty(map.get("associatedTable").toString())) {
                    CustomContent customContent = new CustomContent();
                    customContent.setId(UUIDUtil.getUUID());
                    customContent.setAssociatedTable(map.get("associatedTable").toString());
                    customContent.setPatientId(map.get("patientId").toString());
                    customContent.setDataTime(format.parse(map.get("dataTime").toString()));
                    customContent.setCreateTime(newDate);
                    customContent.setAssociatedTableId(inOutAmount.getId());
                    customContent.setContentOne(map.containsKey("contentOne") && StringUtils.isNotEmpty(map.get("contentOne").toString()) ? map.get("contentOne").toString() : null);
                    customContent.setContentTwo(map.containsKey("contentTwo") && StringUtils.isNotEmpty(map.get("contentTwo").toString()) ? map.get("contentTwo").toString() : null);
                    customContent.setContentThree(map.containsKey("contentThree") && StringUtils.isNotEmpty(map.get("contentThree").toString()) ? map.get("contentThree").toString() : null);
                    customContent.setContentFour(map.containsKey("contentFour") && StringUtils.isNotEmpty(map.get("contentFour").toString()) ? map.get("contentFour").toString() : null);
                    customContent.setContentFive(map.containsKey("contentFive") && StringUtils.isNotEmpty(map.get("contentFive").toString()) ? map.get("contentFive").toString() : null);
                    customContent.setContentSix(map.containsKey("contentSix") && StringUtils.isNotEmpty(map.get("contentSix").toString()) ? map.get("contentSix").toString() : null);
                    customContent.setContentSeven(map.containsKey("contentSeven") && StringUtils.isNotEmpty(map.get("contentSeven").toString()) ? map.get("contentSeven").toString() : null);
                    customContent.setContentEight(map.containsKey("contentEight") && StringUtils.isNotEmpty(map.get("contentEight").toString()) ? map.get("contentEight").toString() : null);
                    customContent.setContentNine(map.containsKey("contentNine") && StringUtils.isNotEmpty(map.get("contentNine").toString()) ? map.get("contentNine").toString() : null);
                    customContent.setContentTen(map.containsKey("contentTen") && StringUtils.isNotEmpty(map.get("contentTen").toString()) ? map.get("contentTen").toString() : null);
                    customContent.setStatus("1");
                    customContentService.insert(customContent);
                }
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "成功");
            }
            if (json.get("msg").toString().equals("成功")) {


            }


        } catch (Exception e) {
            logger.info("病人管理-护理文书-护理单文书-出入量-保存出入量:" + e);
            e.printStackTrace();
        }
        return json.toString();
    }


    /**
     * 病人管理-护理文书-护理单文书-出入量-根据条件查询出入量列表(新的直接查10个字段)
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryInOutAmountList", method = RequestMethod.POST)
    @ResponseBody
    public String queryInOutAmountList(@RequestBody(required = false) Map<String, Object> map) throws
            ParseException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map == null || !map.containsKey("patientId") || StringUtils.isEmpty(map.get("patientId").toString())) {
            json.put("code", HttpCode.NO_PATIENT_CODE.getCode());
            json.put("msg", "请选择病人");
            return json.toString();
        }
        if (!map.containsKey("hour")) {
            json.put("msg", "查询时间跨度小时为空，查询失败");
            return json.toString();
        }
        if (!map.containsKey("startTime")) {
            json.put("msg", "查询开始时间为空，查询失败");
            return json.toString();
        }
        Date endTime = getLaterHoursDate(yyyyMMddHHmmssSdfToDate(String.valueOf(map.get("startTime"))), Long.valueOf(String.valueOf(map.get("hour"))));
        map.put("endTime", yyyyMMddHHmmssSdfToString(endTime));
        if (map != null && map.containsKey("start")) {
            int totalCount = inOutAmountService.getInOutAmountNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        //先查询有哪些自定义字段，放入查询条件中
        Map<String, Object> m = new HashMap<>();
        m.put("status", 1);
        m.put("associatedTable", "table_in_out_amount");//关联表名
        List<CustomField> list = customFieldService.queryList(m);
        if (list != null && list.size() > 0) {
            map.put("list", list);
        }
        List<Map<String, Object>> amountList = inOutAmountService.queryInOutAmountList(map);
        if (amountList != null && amountList.size() > 0) {
            if (amountList.get(0).get("order_name").toString().contains("小结") || amountList.get(0).get("order_name").toString().contains("总结")) {
                amountList.remove(0);
            }
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(amountList));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    @ApiOperation("查询生命体征中需要同步的出入量数据")
    @RequestMapping(value = "/queryVitalSignData", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult queryVitalSignData(@RequestBody Map<String, Object> map) {
        return inOutAmountService.queryVitalSignData(map);
    }

    @ApiOperation("查询生命体征中需要同步的出入量数据")
    @RequestMapping(value = "/useSignSurplus", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult updateUseSign(@RequestBody Map<String, Object> map) {
        return inOutAmountService.updateUseSign(map);
    }

    /**
     * 查询是否可以进行修改出入量数据
     *
     * @param map
     * @return
     */
    @ApiOperation("查询出入量数据是否存在沿用数据")
    @RequestMapping(value = "/byParentIdCount", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult isUpdateData(@RequestBody Map<String, Object> map) {
        return inOutAmountService.isUpdateData(map);
    }
}
